/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminFrame.java
 *
 * Created on 2011-11-3, 1:18:36
 */
package view.admin;

import business.DelEmpCmd;
import business.LoginCmd;
import business.LogoutCmd;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Employee;
import model.EmployeeManager;
import view.LoginFrame;

/**
 *
 * @author Administrator
 */
public class AdminFrame extends javax.swing.JFrame implements Observer{

    /** Creates new form AdminFrame */
    public AdminFrame() {
        initComponents();
        
        EmployeeManager.getInstance().addObserver(this);
        update(null, null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        employeesTable = new javax.swing.JTable() {
            @Override
            public boolean isCellEditable(int row,int col){
                return false;
            }
        };
        createEmployeeBtn = new javax.swing.JButton();
        delEmployeeBtn = new javax.swing.JButton();
        logoutBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        employeesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "身份证号", "姓名", "性别", "密码", "权限"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        employeesTable.setName("employeesTable"); // NOI18N
        employeesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(employeesTable);

        createEmployeeBtn.setText("新建");
        createEmployeeBtn.setName("createEmployeeBtn"); // NOI18N
        createEmployeeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createEmployeeBtnActionPerformed(evt);
            }
        });

        delEmployeeBtn.setText("删除");
        delEmployeeBtn.setName("delEmployeeBtn"); // NOI18N
        delEmployeeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delEmployeeBtnActionPerformed(evt);
            }
        });

        logoutBtn.setText("登出");
        logoutBtn.setName("logoutBtn"); // NOI18N
        logoutBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logoutBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 413, Short.MAX_VALUE)
                .addComponent(createEmployeeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(delEmployeeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(delEmployeeBtn)
                    .addComponent(createEmployeeBtn)
                    .addComponent(logoutBtn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createEmployeeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createEmployeeBtnActionPerformed
        JDialog createNewEmployeeDlg = new CreateNewEmployeeDlg(this, true);
        createNewEmployeeDlg.setLocation(this.getLocation());
        createNewEmployeeDlg.setVisible(true);
    }//GEN-LAST:event_createEmployeeBtnActionPerformed

    private void delEmployeeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delEmployeeBtnActionPerformed
        DefaultTableModel tm = (DefaultTableModel) employeesTable.getModel();
        int selectedRow = employeesTable.getSelectedRow();
        if( selectedRow == -1 )
            return;
        String id = (String) tm.getValueAt(selectedRow, 0);
        DelEmpCmd cmd = new DelEmpCmd();
        cmd.setId(id);
        if( cmd.execute(null) ) {
            //do nothing
        }else{
            JOptionPane.showMessageDialog(this, "删除员工失败 ", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_delEmployeeBtnActionPerformed

    private void logoutBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutBtnActionPerformed
        LogoutCmd cmd = new LogoutCmd();
        if( cmd.execute(null) ) {
            new LoginFrame().setVisible(true);
            this.dispose();
        }else{
            JOptionPane.showMessageDialog(this, "登出失败 ", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_logoutBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdminFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AdminFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createEmployeeBtn;
    private javax.swing.JButton delEmployeeBtn;
    private javax.swing.JTable employeesTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton logoutBtn;
    // End of variables declaration//GEN-END:variables

    public void update(Observable o, Object arg) {        
        EmployeeManager em = EmployeeManager.getInstance();
        ArrayList<Employee> employees = em.getEmployees();
        DefaultTableModel  tm = (DefaultTableModel) employeesTable.getModel();
        tm.setRowCount(0);
        for(Employee employee : employees) {
            String[] arr=new String[5];
            arr[0]=employee.getId();
            arr[1]=employee.getName();
            arr[2]=employee.isMale()?"男":"女";
            arr[3]=employee.getPwd(); 
            arr[4]=employee.getRole();
            tm.addRow(arr);
        }
        employeesTable.invalidate();
    }
}
